import React, { useState, useEffect } from 'react';

const ControlPanel = ({ 
  center, 
  zoom, 
  showTiles, 
  showVectors, 
  onCenterChange, 
  onZoomChange, 
  onToggleTiles, 
  onToggleVectors 
}) => {
  const [localCenter, setLocalCenter] = useState(center);
  const [localZoom, setLocalZoom] = useState(zoom);
  const [serverStatus, setServerStatus] = useState('checking');

  // 检查服务器状态
  useEffect(() => {
    const checkServerStatus = async () => {
      try {
        const response = await fetch('/api/health');
        if (response.ok) {
          const data = await response.json();
          setServerStatus('online');
        } else {
          setServerStatus('error');
        }
      } catch (error) {
        setServerStatus('offline');
      }
    };

    checkServerStatus();
    const interval = setInterval(checkServerStatus, 30000); // 每30秒检查一次
    
    return () => clearInterval(interval);
  }, []);

  // 同步中心点变化
  useEffect(() => {
    setLocalCenter(center);
  }, [center]);

  // 同步缩放级别变化
  useEffect(() => {
    setLocalZoom(zoom);
  }, [zoom]);

  // 处理中心点输入
  const handleCenterChange = (index, value) => {
    const newCenter = [...localCenter];
    const numValue = parseFloat(value);
    
    if (!isNaN(numValue)) {
      newCenter[index] = numValue;
      setLocalCenter(newCenter);
    }
  };

  // 应用中心点变化
  const applyCenterChange = () => {
    onCenterChange(localCenter);
  };

  // 处理缩放级别输入
  const handleZoomChange = (value) => {
    const numValue = parseFloat(value);
    if (!isNaN(numValue) && numValue >= 0 && numValue <= 10) {
      setLocalZoom(numValue);
      onZoomChange(numValue);
    }
  };

  // 预设位置
  const presetLocations = [
    { name: '北京', center: [116.3974, 39.9093], zoom: 8 },
    { name: '上海', center: [121.4737, 31.2304], zoom: 8 },
    { name: '广州', center: [113.2644, 23.1291], zoom: 8 },
    { name: '深圳', center: [114.0579, 22.5431], zoom: 8 },
    { name: '全球视图', center: [0, 0], zoom: 0 }
  ];

  // 跳转到预设位置
  const goToPreset = (preset) => {
    onCenterChange(preset.center);
    onZoomChange(preset.zoom);
    setLocalCenter(preset.center);
    setLocalZoom(preset.zoom);
  };

  // 服务器状态显示
  const getServerStatusText = () => {
    switch (serverStatus) {
      case 'online':
        return { text: '在线', color: '#10b981' };
      case 'offline':
        return { text: '离线', color: '#ef4444' };
      case 'error':
        return { text: '错误', color: '#f59e0b' };
      default:
        return { text: '检查中...', color: '#6b7280' };
    }
  };

  const statusInfo = getServerStatusText();

  return (
    <div className="control-panel">
      <div className="control-group">
        <h3 style={{ color: 'white', marginBottom: '16px', fontSize: '16px' }}>
          地图控制
        </h3>
        
        {/* 服务器状态 */}
        <div className="control-group">
          <div className="control-label">服务器状态</div>
          <div style={{ 
            display: 'flex', 
            alignItems: 'center', 
            fontSize: '14px',
            color: statusInfo.color 
          }}>
            {serverStatus === 'checking' && <span className="loading"></span>}
            {statusInfo.text}
          </div>
        </div>

        {/* 中心点坐标 */}
        <div className="control-group">
          <div className="control-label">中心点坐标</div>
          <div style={{ display: 'flex', gap: '8px', marginBottom: '8px' }}>
            <input
              type="number"
              className="control-input"
              value={localCenter[0]}
              onChange={(e) => handleCenterChange(0, e.target.value)}
              placeholder="经度"
              step="0.0001"
              style={{ flex: 1 }}
            />
            <input
              type="number"
              className="control-input"
              value={localCenter[1]}
              onChange={(e) => handleCenterChange(1, e.target.value)}
              placeholder="纬度"
              step="0.0001"
              style={{ flex: 1 }}
            />
          </div>
          <button 
            className="btn" 
            onClick={applyCenterChange}
            style={{ width: '100%' }}
          >
            应用坐标
          </button>
        </div>

        {/* 缩放级别 */}
        <div className="control-group">
          <div className="control-label">缩放级别: {zoom.toFixed(1)}</div>
          <input
            type="range"
            min="0"
            max="10"
            step="0.1"
            value={localZoom}
            onChange={(e) => handleZoomChange(e.target.value)}
            className="control-input"
            style={{ width: '100%', padding: '0' }}
          />
        </div>

        {/* 图层控制 */}
        <div className="control-group">
          <div className="control-label">图层显示</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
            <label style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer' }}>
              <input
                type="checkbox"
                checked={showTiles}
                onChange={onToggleTiles}
                style={{ margin: 0 }}
              />
              <span style={{ color: 'white', fontSize: '14px' }}>显示瓦片</span>
            </label>
            <label style={{ display: 'flex', alignItems: 'center', gap: '8px', cursor: 'pointer' }}>
              <input
                type="checkbox"
                checked={showVectors}
                onChange={onToggleVectors}
                style={{ margin: 0 }}
              />
              <span style={{ color: 'white', fontSize: '14px' }}>显示矢量数据</span>
            </label>
          </div>
        </div>

        {/* 预设位置 */}
        <div className="control-group">
          <div className="control-label">快速定位</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px' }}>
            {presetLocations.map((preset, index) => (
              <button
                key={index}
                className="btn"
                onClick={() => goToPreset(preset)}
                style={{ 
                  fontSize: '12px', 
                  padding: '6px 8px',
                  background: 'rgba(255, 255, 255, 0.1)'
                }}
              >
                {preset.name}
              </button>
            ))}
          </div>
        </div>

        {/* 操作提示 */}
        <div className="control-group">
          <div style={{ 
            fontSize: '11px', 
            color: '#a0aec0', 
            lineHeight: '1.4',
            borderTop: '1px solid rgba(255, 255, 255, 0.1)',
            paddingTop: '8px'
          }}>
            <div>• 拖拽地图平移</div>
            <div>• 滚轮缩放</div>
            <div>• 双击快速缩放</div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ControlPanel;